﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace SocketDemo
{
    class SocketClient
    {
        public string GetResultMsg(string sendMsg)
        {
            string result = string.Empty;
            try
            {
                int port = 2000;
                string host = "127.0.0.1";

                IPAddress ip = IPAddress.Parse(host);

                IPEndPoint ipe = new IPEndPoint(ip, port);

                Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                //result = "Conneting...";

                s.Connect(ipe);//连接服务器

                byte[] bs = Encoding.ASCII.GetBytes(sendMsg);//把字节串编码为字接数组

                //Console.WriteLine("Send Message");

                s.Send(bs, bs.Length, 0);//发送信息


                /*接收服务器返回的信息*/

                string recvStr = string.Empty;

                byte[] recvBytes = new byte[1024];

                int bytes = s.Receive(recvBytes, recvBytes.Length, 0);

                recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);

                result=string.Format("client get message:{0}", recvStr);//显示服务器返回信息

                s.Close();
            }
            catch (SocketException ex)
            {
                result=string.Format("SocketException:{0}", ex);
            }
            //result = string.Format("Press Enter to Exit");
            return result;
        }
    }
}
